package com.jd.fruit.model.admin.shop;

import java.util.ArrayList;
import java.util.List;

import com.jd.fruit.common.annotation.Table;
import com.jd.fruit.common.model.BaseModel;
import com.jd.fruit.common.util.StringUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

/**
 * 商品
 * 
 */
@SuppressWarnings("serial")
@Table("t_goods")
public class Goods extends BaseModel<Goods> { 
	public static final Goods dao = new Goods();
	/**
	 * 保存商品
	 * @param role
	 */
	public String save(Goods goods){
		try {
			String key=StringUtil.getKey();
			goods.set("id",key);
			goods.save();
			return key;
		} catch (Exception e) {
			throw new RuntimeException("商品保存异常！", e);
		}
	}
	
	/**
	 * 根据商品编号查询商品信息
	 * @param goodsid
	 * @return
	 */
	public Goods findByGoodsNo(Object goodsid){
		String sql="SELECT * FROM `t_goods` WHERE goods_no=?";
		return this.findFirst(sql, goodsid);
	}
	
	/**
	 * 商品分页查询
	 * @param pageNumber
	 * @param pageSize
	 * @param goods
	 * @return
	 */
	public Page<Record> list(int pageNumber,int pageSize,Goods goods){
		List<Object> whereParams = new ArrayList<Object>();
		StringBuffer whereSql=new StringBuffer(" FROM `t_goods_sku`  tga JOIN `t_goods` tg ON tga.`goods_id`=tg.`id`");

		if(goods!=null){
			String name=goods.getStr("goods_name");
			String sn=goods.getStr("goods_sn");
			
			if(StrKit.notBlank(sn)){
				whereParams.add(sn);
	        	whereSql.append(" and tg.goods_sn=? ");
			}
			if(StrKit.notBlank(name)){
				whereParams.add(name);
				whereSql.append(" and tg.goods_name=? ");
			}
		}
		whereSql.append("GROUP BY tga.`goods_id` ");
		
		return Db.paginate(pageNumber,pageSize,"select tg.*, SUM(tga.`stocks`) AS stocks, SUM(tga.`sales`) AS sales ",whereSql.toString(),whereParams.toArray());
	}	
	
	@Override
	public void initWhere() {
		// TODO Auto-generated method stub
		
	}
	
	
}
